﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using SF.Code.Extension.ComponentHelper;
using SF.Code.Extension.DebuggingHelper;
using SF.Code.Extension.HttpHelper.Downloader;
using SF.Code.Extension.WinAPI;
using SG.Ling.AutoTranslator.App;
using SG.Ling.AutoTranslator.Common;

namespace SG.Ling.AutoTranslator.Translation
{
    public partial class UserForm : Form
    {
        private UserFormSettings _settings;

        public UserForm()
        {
            InitializeComponent();

            Disposed += UserFormDisposed;
        }

        private void UserFormDisposed(object sender, EventArgs e)
        {
            try
            {
                if (_settings != null)
                    _settings.WriteToAppData();
            }
            catch (Exception exception)
            {
                GC.KeepAlive(exception);
            }
        }

        private void UserFormClipboardTextChanged(object sender, ClipboardTextChangedEventArgs e)
        {
            TranslateAsync(e);
        }

        private void UserFormLoad(object sender, EventArgs e)
        {
            if (ComponentEx.DesignMode)
                return;

            _settings = UserFormSettings.ReadFromAppData();

            SetupOptions();

            SetupTaskbarIcons();

            SetupLanguageSelectors();

            DisplayHitRatio();

            Infrastructure.MainPumpForm.ClipboardTextChanged += UserFormClipboardTextChanged;
        }

        private void SetupOptions()
        {
            showBallonToolStripMenuItem.Checked = _settings.ShowBalloon;
            autoClipboardToolStripMenuItem.Checked = _settings.AutoClipboard;
            autoSpeakToolStripMenuItem.Checked = speakControl1.SpeakAutomatically;
            speakControl1.SpeakAutomaticallyChanged += speakControl1_SpeakAutomaticallyChanged; 
        }

        void speakControl1_SpeakAutomaticallyChanged(object sender, EventArgs e)
        {
            autoSpeakToolStripMenuItem.Checked = speakControl1.SpeakAutomatically;
        }

        private void SendAppCmd(Command cmd)
        {
            CommandGroup.Application.SendCommand(cmd, Infrastructure.Handle);
        }

        private void NotifyIconDoubleClick(object sender, EventArgs e)
        {
            SendAppCmd(Command.Show);
        }

        public bool CloseFromMenu { private get; set; }

        private void ExitToolStripMenuItemClick(object sender, EventArgs e)
        {
            SendAppCmd(Command.Close);
        }


        private void UserFormFormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CloseFromMenu && Debugger.IsAttached)
                SendAppCmd(Command.Close);

            if (ComponentEx.DesignMode || CloseFromMenu) return;

            e.Cancel = true;
            Visible = false;
        }

        private void RestoreToolStripMenuItemClick(object sender, EventArgs e)
        {
            SendAppCmd(Command.Show);
        }

        private void HideToolStripMenuItemClick(object sender, EventArgs e)
        {
            SendAppCmd(Command.Hide);
        }

        private void ButtonFlipLangsClick(object sender, EventArgs e)
        {
            FlipLanguages();
        }

        private void UserFormKeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                SendAppCmd(Command.Hide);
        }

        private void BatchTranslatorErrorOccurred(object sender, UnhandledExceptionEventArgs e)
        {
            BatchTranslatorErrorOccurred(sender, e.ExceptionObject);
        }

        private void BatchTranslatorTranslationCompleted(object sender, WebClientBagResultEventArgs<TranslationTuple> e)
        {
            BatchTranslatorTranslationCompleted(sender, e.Result, e.IsFromCache);
        }

        private void comboBoxSource_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ComboBoxValueChanged(comboBoxSource, comboBoxTarget);
        }

        private void comboBoxTarget_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ComboBoxValueChanged(comboBoxTarget, comboBoxSource);
        }

        private void timerResetNotifyIcon_Tick(object sender, EventArgs e)
        {
            timerResetNotifyIcon.Stop();
            notifyIconTaskbar.Icon = _normalTaskbarIcon;
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _tbEdit.Copy();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _tbEdit.Paste(DataFormats.GetFormat(DataFormats.UnicodeText));
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _tbEdit.Cut();
        }

        private void _tbEdit_Enter(object sender, EventArgs e)
        {
            TranslateAsync(_tbEdit.Text);
        }

        private void autoClipboardToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            var @checked = autoClipboardToolStripMenuItem.Checked;
            _settings.AutoClipboard = @checked;
            notifyIconTaskbar.Icon = @checked ? Properties.Resources.translator_auto_clip : Properties.Resources.translator;
        }

        private void InvokeOrDirect(Action action)
        {
            try
            {
                if (IsDisposed)
                    return;

                if (InvokeRequired)
                    Invoke(action);
                else
                    action();
            }
            catch (Exception exception)
            {
                exception.Log();
            }
        }

        private void showBallonToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            _settings.ShowBalloon = showBallonToolStripMenuItem.Checked;
        }

        private void autoSpeakToolStripMenuItem_Click(object sender, EventArgs e)
        {
            speakControl1.SpeakAutomatically = autoSpeakToolStripMenuItem.Checked;
        }

        private void pasteTranslateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _tbEdit.Clear();
            TranslateAsync(Clipboard.GetText(TextDataFormat.UnicodeText));
        }

    }
}
